import { App } from "antd";
// import { navigate } from "../utils/fun.ts";
import { useNavigate } from "./useNavigate.ts";
import { useConfig } from "./D8dConfigProvider.tsx";
import qs from "qs";

// 定义请求选项接口
export interface RequestOptions<T = any> {
  url: string;
  method?: "GET" | "POST" | "PUT" | "DELETE";
  data?: any;
  headers?: Record<string, string>;
  success?: (result: T) => void;
  fail?: (error: any) => void;
}

export const useApiRequest = () => {
  const { message } = App.useApp();
  const { appConfig, token, loaderPath } = useConfig();
  const apiBaseUrl = appConfig?.apiBaseUrl;
  const navigate = useNavigate();
  const request = async <T = any>(options: RequestOptions<T>): Promise<T | undefined> => {
    const { url, method, data, success, fail } = options;
    let query = "";

    try {
      if (method === "GET") {
        query = qs.stringify(data);
        query = query ? `?${query}` : "";
      }
      const fullUrl = `${apiBaseUrl}${url}${query}`;
      const response = await fetch(fullUrl, {
        method: method || "GET",
        headers: {
          "Content-Type": "application/json",
          ...(options.headers || {}),
        },
        body:
          method === "POST" || method === "PUT" ? JSON.stringify(data) : null,
      });

      if (!response.ok && response.status !== 401) {
        const errorData = await response.json().catch(() => null);
        const errorMessage = errorData?.message || response.statusText;

        if (fail) fail?.(`请求错误: ${errorMessage}`);
        else message.error(`请求错误: ${errorMessage}`);
        
        return;
      } else if(response.status === 401) {
        console.log("401错误");
        console.log("loaderPath", loaderPath);
        navigate(`/${loaderPath}`);
        message.error("请先登录");
        return;
      }

      const result = await response.json() as T;

      // if ((result as any).code === 401) {
      //   navigate(`/${loaderPath}`);
      //   message.error((result as any).message || "未授权访问");
      //   return;
      // }

      success?.(result);

      return result;
    } catch (error: any) {
      console.error(
        "There has been a problem with your fetch operation:",
        error
      );
      if (fail) fail?.("网络请求异常，请稍后再试");
      else message.error("网络请求异常，请稍后再试");
    }
  };

  const requestWithToken = async <T = any>(options: RequestOptions<T>): Promise<T | undefined> => {
    return request({
      ...options,
      headers: {
        ...options.headers,
        Authorization: `Bearer ${token}`
      }
    });
  };

  return { request, requestWithToken };
};
